package utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import utils.DataMap;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.ModelAndView;



/**
 * @author Administrator
 * 
 */
public class PUtil {

	/**
	 * 시스템 파일명 생성을 위한 랜덤값 취하기. 이미지명 등 으로 사용 참고
	 * /static_root/common_jsp/FILE_UPLOAD.jsp
	 * 
	 * @return
	 */
	public static String getRandomKey() {
		return RandomStringUtils.randomAlphanumeric(20);
	}

	/**
	 * 문자형을 float 형으로 전환한다. Auth : yumi Date : 2011. 08. 10
	 * 
	 * @param
	 * @param
	 * @return float
	 * @TODO : TODO
	 */

	public static String getFloat(String str, String win_cnt) {
		String num = null;
		double temp = 0;

		temp = (Math.floor((Integer.parseInt(str) / Integer.parseInt(win_cnt)) * 100));
		num = getDeimalFormat(temp);
		return num;

	}

	/**
	 * 포맷관련
	 */
	public static String getDeimalFormat(int number) {
		return getDecimalFormat(number, ".##");
	}

	public static String getDeimalFormat(long number) {
		return getDecimalFormat(number, "###,###,###,###");
	}

	public static String getDeimalFormat(double number) {
		return getDecimalFormat(number, "###,###,###,###");
	}

	public static String getDecimalFormat(int number, String pattern) {
		DecimalFormat decimalFormat = new DecimalFormat(pattern);
		return decimalFormat.format(number);
	}

	public static String getDecimalFormat(float number, String pattern) {
		DecimalFormat decimalFormat = new DecimalFormat(pattern);
		return decimalFormat.format(number);
	}

	public static String getDecimalFormat(double number, String pattern) {
		DecimalFormat decimalFormat = new DecimalFormat(pattern);
		return decimalFormat.format(number);
	}

	public static boolean isNullTrimSpace(String str) {
		if (str == null || "".equals(str.trim()))
			return true;
		return false;
	}

	public static String getSimpleSizeFormat(long value) {
		String size = "";
		if ((1024 < value) && (value < 1024 * 1024))
			size = getDecimalFormat((float) value / 1024, "###,###.##") + " KB";
		else if (1024 * 1024 <= value)
			size = getDecimalFormat((float) value / (1024 * 1024), "###,###.##") + " MB";
		else if (1024 * 1024 * 1024 <= value)
			size = getDecimalFormat((float) value / (1024 * 1024), "###,###,###.##") + " GB";
		else
			size = getDecimalFormat((float) value, "###,###.##") + " Bytes";

		return size;
	}

	/**
	 * 퍼센트로 데이타 포맷 변환하기 Auth : yumi Date : 2011. 08. 11
	 * 
	 * @param
	 * @param
	 * @return String
	 * @TODO : TODO
	 */
	public static String getSimpleSizePercent(double voteCnt, String total) {
		String temp = null;
		NumberFormat pf = NumberFormat.getPercentInstance();

		double cnt = Double.parseDouble(total);
		temp = pf.format(voteCnt / cnt);
		return temp;

	}

	public static void htmlAlertPrintClose(HttpServletResponse res, String message) throws IOException {
		res.setContentType("text/html; charset=utf-8");
		PrintWriter out = res.getWriter();
		out.println("<script type=\"text/javascript\">");
		out.println("alert('" + message + "');window.close();");
		out.println("</script>");
	}

	/**
	 * 문자열 처리
	 * 
	 * 
	 */

	// 태그를 삭제하고 byte로 자름
	public static String parseStringByBytes(String raw, int len) {
		if (raw == null)
			return null;

		raw = removeTag(raw);
		String[] ary = null;
		String returnStr = "";

		try {
			// raw 의 byte
			byte[] rawBytes = raw.getBytes();
			int rawLength = rawBytes.length;

			int index = 0;
			int minus_byte_num = 0;
			int offset = 0;

			if (rawLength > len) {
				int aryLength = (rawLength / len) + (rawLength % len != 0 ? 1 : 0);
				ary = new String[aryLength];

				for (int i = 0; i < 1; i++) {
					minus_byte_num = 0;
					offset = len;
					if (index + offset > rawBytes.length) {
						offset = rawBytes.length - index;
					}
					for (int j = 0; j < offset; j++) {
						if (((int) rawBytes[index + j] & 0x80) != 0) {
							minus_byte_num++;
						}
					}
					if (minus_byte_num % 3 != 0) {
						offset -= minus_byte_num % 3;
					}
					ary[i] = new String(rawBytes, index, offset);
					index += offset;

				}
				returnStr = ary[0] + "...";
			} else {
				ary = new String[] { raw };
				returnStr = ary[0];
			}
		} catch (Exception e) {

		}
		return returnStr;
	}

	public static String getLimitChar(String string, int len) {
		if (len == 0)
			return string;
		else
			return getLimitChar(string, len, '+', "...");
	}

	public static String getLimitChar(String str, int length, char type, String tail) {
		if (length == 0)
			return str;

		if (str == null || str.length() == 0)
			return "";

		byte[] bytes = str.getBytes();
		int len = bytes.length;
		int counter = 0;

		if (length >= len)
			return str;

		StringBuffer sb = new StringBuffer();
		sb.append(str);
		for (int i = 0; i < length - len; i++) {
			sb.append(' ');
		}

		for (int i = length - 1; i >= 0; i--) {
			if (((int) bytes[i] & 0x80) != 0)
				counter++;
		}
		String f_str = null;
		if (type == '+') {
			f_str = new String(bytes, 0, length + (counter % 2));
		} else if (type == '-') {
			f_str = new String(bytes, 0, length - (counter % 2));
		} else {
			f_str = new String(bytes, 0, length - (counter % 2));
		}

		return f_str + tail;
	}

	public static String nullTrimReplace(String str) {
		return nullTrimReplace(str, "");
	}

	public static String nullTrimReplace(String str, String replace) {
		if (str == null || str.trim().length() == 0)
			return replace;
		return str;
	}

	public static String nullTrimReplace(Object str, String replace) {
		if (str == null)
			return replace;
		str = str.toString().trim();
		if (str.equals("")) {
			return replace;
		} else {
			return str.toString().trim();
		}
	}

	public static String nullTrimReplace(Object str) {
		if (str == null)
			return "";
		return str.toString().trim();
	}

	/*
	 * 주어진 길이보다 짧은 문자열의 앞부분을 특정 문자로 채워주는 메소드
	 * 
	 * @ para : 문자열, 채울 문자, 문자열길이
	 */
	public static String fillChar(String str, char fill, int length) {
		StringBuffer fixed = null;
		int src_len = 0;
		if (str == null)
			return null;
		src_len = str.length();
		fixed = new StringBuffer(str);
		for (; ++src_len <= length;) {
			fixed.insert(0, fill);
		}
		return fixed.toString();
	}

	public static String fillChar(int digit, char fill, int length) {
		StringBuffer fixed = null;
		String str = Integer.toString(digit);
		int src_len = 0;
		if (str == null)
			return null;
		src_len = str.length();
		fixed = new StringBuffer(str);
		for (; ++src_len <= length;) {
			fixed.insert(0, fill);
		}
		return fixed.toString();
	}

	/*
	 * 주어진 문자열의 주어진 길이 다음 문자들을 특정 문자로 바꿔주는 메서드
	 * 
	 * @ para : 문자열, 바꿀 문자, 주어진 길이 다음문자를 바꿈
	 */
	public static String changeNextChar(String str, char change_char, int length) {
		if (str == null)
			return null;
		int str_len = str.length();
		if (str_len <= length)
			return str;

		str = str.substring(0, length);
		StringBuffer strBuf = new StringBuffer(str);
		for (int i = 0; i < str_len; i++) {
			strBuf.append(change_char);
		}
		return strBuf.toString();
	}

	/**
	 * 숫자문자열을 xx,xxx 같은 형식의 콤마숫자열로 변환
	 * 
	 */
	public static String toCommaDigit(String src) {
		int intsrc = 0;
		int len = 0;

		if (src == null)
			return src;
		StringBuffer cd = null;

		try {
			intsrc = Integer.parseInt(src);
		} catch (NumberFormatException e) {
			return null;
		}

		src = "" + intsrc;
		cd = new StringBuffer("" + intsrc);
		len = src.length();
		for (int i = 1; i <= (len - 1) / 3; ++i) {
			cd.insert(len - 3 * i, ',');
		}
		return cd.toString();
	}

	/**
	 * 숫자를 xx,xxx 같은 형식의 콤마숫자열로 변환
	 * 
	 */
	public static String toCommaDigit(int src) {
		String srcstr = null;
		int len = 0;
		StringBuffer cd = null;

		srcstr = "" + Math.abs(src);

		cd = new StringBuffer(srcstr);
		len = srcstr.length();
		for (int i = 1; i <= (len - 1) / 3; ++i) {
			cd.insert(len - 3 * i, ',');
		}

		if (src < 0)
			cd.insert(0, '-');
		return cd.toString();
	}

	/**
	 * 숫자를 xx,xxx 같은 형식의 콤마숫자열로 변환
	 * 
	 */
	public static String toCommaDigit(long src) {
		String srcstr = null;
		int len = 0;
		StringBuffer cd = null;

		srcstr = "" + Math.abs(src);

		cd = new StringBuffer(srcstr);
		len = srcstr.length();
		for (int i = 1; i <= (len - 1) / 3; ++i) {
			cd.insert(len - 3 * i, ',');
		}

		if (src < 0)
			cd.insert(0, '-');
		return cd.toString();
	}

	/************ HTML ******************/

	/**
	 * 줄바꿈문자 <br>
	 * 로
	 * 
	 * @param str
	 * @return
	 */
	public static String cr2br(String str) {
		return StringUtils.replace(StringUtils.replace(str, "\n\r", "<br/>"), "\n", "<br/>");
	}

	public static String cr2br2(String str) {
		return StringUtils.replace(str, "\n", "");
	}

	public static String cr2br3(String str) {
		return StringUtils.replace(str, "&nbsp", "");
	}

	public static String escapeHtml(String string) {
		return StringEscapeUtils.escapeHtml(string);
	}

	public static String unEscapeHtml(String str) {
		return StringEscapeUtils.unescapeHtml(str);
	}

	/**
	 * "",'' 제거 (http://www.jakartaproject.com) kiho
	 * 
	 * @param s
	 * @return
	 */
	public static String removeDoubleAndSingleQuote(String str) {
		if (str == null)
			return "";
		String aa = str.replace("\"", "");
		String bb = aa.replace("\'", "");
		return bb;
	}

	/**
	 * p제거 Auth : munho Date : 2011. 09. 08
	 * 
	 * @param
	 * @param
	 * @return String
	 * @TODO : TODO
	 */
	public static String removeDoubleQuoteP(String str) {
		if (str == null)
			return "";
		String aa = str.replace("\"", "");
		String bb = aa.replace("\'", "");
		String cc = bb.replace("<p>", "");
		String dd = cc.replace("</p>", "");
		return dd;
	}

	/**
	 * 태그제거 (http://www.jakartaproject.com) 유니콘보드 유틸
	 * 
	 * @param s
	 * @return
	 */
	public static String removeTag(String s) {
		if (s == null)
			return "";

		final int NORMAL_STATE = 0;
		final int TAG_STATE = 1;
		final int START_TAG_STATE = 2;
		final int END_TAG_STATE = 3;
		final int SINGLE_QUOT_STATE = 4;
		final int DOUBLE_QUOT_STATE = 5;
		int state = NORMAL_STATE;
		int oldState = NORMAL_STATE;
		char[] chars = s.toCharArray();
		StringBuffer sb = new StringBuffer();
		char a;
		for (int i = 0; i < chars.length; i++) {
			a = chars[i];
			switch (state) {
			case NORMAL_STATE:
				if (a == '<')
					state = TAG_STATE;
				else
					sb.append(a);
				break;
			case TAG_STATE:
				if (a == '>')
					state = NORMAL_STATE;
				else if (a == '\"') {
					oldState = state;
					state = DOUBLE_QUOT_STATE;
				} else if (a == '\'') {
					oldState = state;
					state = SINGLE_QUOT_STATE;
				} else if (a == '/')
					state = END_TAG_STATE;
				else if (a != ' ' && a != '\t' && a != '\n' && a != '\r' && a != '\f')
					state = START_TAG_STATE;
				break;
			case START_TAG_STATE:
			case END_TAG_STATE:
				if (a == '>')
					state = NORMAL_STATE;
				else if (a == '\"') {
					oldState = state;
					state = DOUBLE_QUOT_STATE;
				} else if (a == '\'') {
					oldState = state;
					state = SINGLE_QUOT_STATE;
				} else if (a == '\"')
					state = DOUBLE_QUOT_STATE;
				else if (a == '\'')
					state = SINGLE_QUOT_STATE;
				break;
			case DOUBLE_QUOT_STATE:
				if (a == '\"')
					state = oldState;
				break;
			case SINGLE_QUOT_STATE:
				if (a == '\'')
					state = oldState;
				break;
			}
		}
		return sb.toString();
	}

	/**
	 * 날짜관련
	 */
	public static String getDate(java.util.Date date, String format) {
		if (date == null || format == null)
			return "";
		SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.ENGLISH);
		return sdf.format(date);
	}

	public static String getFormatDate(String format) {
		return getFormatDate(new Date(), format);
	}

	public static String getFormatDate(java.util.Date date, String format) {
		return (new java.text.SimpleDateFormat(format)).format(date);
	}

	public static String getCurrentYear() {
		String currYear = null;
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
		Date currentTime = new Date();
		return currYear = formatter.format(currentTime);
	}

	public static String getCurrentMonth() {
		SimpleDateFormat formatter = new SimpleDateFormat("MM");
		Date currentTime = new Date();
		return formatter.format(currentTime);
	}

	public static String getCurrentDay() {
		SimpleDateFormat formatter = new SimpleDateFormat("dd");
		Date currentTime = new Date();
		return formatter.format(currentTime);
	}

	public static String getCurrentMonth01() {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		int field = calendar.getActualMinimum(Calendar.DATE);
		return getDate(new Date(), "yyyyMM") + (field < 10 ? "0" + field : String.valueOf(field));
	}

	public static String getCurrentMonth31() {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		return getDate(new Date(), "yyyyMM") + calendar.getActualMaximum(Calendar.DATE);
	}

	public static String getCurrentDate(String format) {
		return getDate(new Date(), format);
	}

	public static String getCurrentDate() {
		return getDate(new Date(), "yyyyMMdd");
	}

	public static String getDate(int day) {
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, day);
		return getDate(calendar.getTime(), "yyyyMMdd");
	}

	public static String getDate(int day, String format) {
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, day);
		return getDate(calendar.getTime(), format);
	}

	public static int getLastDay(int intYear, int intMonth) {
		Calendar cal = new GregorianCalendar();
		cal.setLenient(false);
		cal.set(intYear, intMonth - 1, 1);
		return cal.getActualMaximum(GregorianCalendar.DATE);
	}

	public static int getLastDay(String yyyymm) {
		Calendar cal = new GregorianCalendar();
		cal.setLenient(false);
		cal.set(Integer.parseInt(yyyymm.substring(0, 4)), Integer.parseInt(yyyymm.substring(4)) - 1, 1);
		return cal.getActualMaximum(GregorianCalendar.DATE);
	}

	public static int getFirstDayOfWeek(String yyyymm) {
		Calendar cal = new GregorianCalendar();
		cal.setLenient(false);
		cal.set(Integer.parseInt(yyyymm.substring(0, 4)), Integer.parseInt(yyyymm.substring(4)) - 1, 1);
		return cal.get(Calendar.DAY_OF_WEEK);
	}

	// 받은 날짜에 증가 시키고 싶은 날짜 만큼 증가시킨다.
	// kiho
	public static String addDay(String day, int inc) throws ParseException {
		Date today = new SimpleDateFormat("yyyyMMddHHmm").parse(day);
		Date addDay = new Date(today.getTime() + (inc * ((long) 1000 * 60 * 60 * 24)));

		String pattern = "yyyyMMddHHmm";
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);

		String addDayString = sdf.format(addDay);

		return addDayString;
	}

	/**
	 * 날짜를 받아 해당 날짜가 속한 달의 일수를 리턴
	 * 
	 * @param date
	 * @param format
	 * @return
	 */
	public static int getMaximumDate(String date, String format) {
		SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.KOREA);
		Calendar calendar = Calendar.getInstance();
		try {
			calendar.setTime(sdf.parse(date));
			return calendar.getActualMaximum(Calendar.DATE);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return 0;
	}

	/**
	 * 지정된 형식의 포맷을 받아 현재의 날짜를 포맷에 맞게 리턴
	 * 
	 * @param format
	 * @return
	 */
	public static String getForamtDate(String format) {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
		return simpleDateFormat.format(new Date());
	}

	public static String getFormatStringDate(String yyyymmdd, String sep) {
		if (yyyymmdd == null || yyyymmdd.length() < 8)
			return "";
		return yyyymmdd.substring(0, 4) + sep + yyyymmdd.substring(4, 6) + sep + yyyymmdd.substring(6);
	}

	public static String getFormatStringDate1(String yyyymmddhhmiss, String sep) {
		if (yyyymmddhhmiss == null || yyyymmddhhmiss.length() < 8)
			return "";
		String c_sta_dt = yyyymmddhhmiss.substring(0, 8);
		return getFormatStringDate(c_sta_dt, sep);
	}

	public static String getFormatStringDate2(String yyyymmddhhmiss, String sep, String sep2) {
		if (yyyymmddhhmiss == null || yyyymmddhhmiss.length() < 14)
			return "";
		String c_sta_dt = yyyymmddhhmiss.substring(0, 14);
		return getFormatStringDate3(c_sta_dt, sep, sep2);
	}

	public static String getFormatStringDate3(String yyyymmdd, String sep, String sep2) {
		if (yyyymmdd == null || yyyymmdd.length() < 14)
			return "";
		return yyyymmdd.substring(0, 4) + sep + yyyymmdd.substring(4, 6) + sep + yyyymmdd.substring(6, 8) + "&nbsp;" + sep2 + yyyymmdd.substring(8, 10) + ":" + yyyymmdd.substring(10, 12) + ":"
				+ yyyymmdd.substring(12, 14) + sep2;
	}

	public static String getFormatStringDate4(String mmdd, String sep) {

		if (mmdd == null || mmdd.length() < 4)
			return "";
		return mmdd.substring(0, 2) + sep + mmdd.substring(2, 4);
	}

	// format 형식의 날짜 문자열을 받아 format2형식으로 변환
	public static String getFormatStringDate(String date, String format, String format2) throws Exception {
		Date dToday = new SimpleDateFormat(format).parse(date);
		return new SimpleDateFormat(format2).format(dToday);
	}

	/**
	 * 경기 시작 시간 및 종료시간 리턴 Auth : yumi Date : 2011. 08. 04
	 * 
	 * @param
	 * @param
	 * @return String
	 * @TODO : TODO
	 */

	public static String getGameTime6(String hhmmss, String sep) {
		if (hhmmss == null || hhmmss.length() < 6)
			return "";
		return hhmmss.substring(0, 2) + sep + hhmmss.substring(2, 4) + sep + hhmmss.substring(4, 6);
	}

	/**
	 * 판정시간 Auth : yumi Date : 2011. 08. 04
	 * 
	 * @param
	 * @param
	 * @return String
	 * @TODO : TODO
	 */
	public static String getGameTime4(String hhmmss, String sep) {
		if (hhmmss == null || hhmmss.length() < 4)
			return "";
		return hhmmss.substring(0, 2) + sep + hhmmss.substring(2, 4);
	}

	/**
	 * 월.일 형식 변환 Auth : yumi Date : 2011. 08. 05
	 * 
	 * @param
	 * @param
	 * @return String
	 * @TODO : TODO
	 */

	public static String getMmdd(String hhmmss, String sep) {
		if (hhmmss == null || hhmmss.length() < 4)
			return "";
		return hhmmss.substring(0, 2) + sep + hhmmss.substring(2, 4);
	}

	/**
	 * @param
	 * @param
	 * @return String
	 * @TODO : TODO
	 */
	public static String getMmdd2(String hhmmss) {
		if (hhmmss == null || hhmmss.length() < 4)
			return "";
		return hhmmss.substring(0, 2) + "월" + hhmmss.substring(2, 4) + "일";
	}

	/**
	 * form에서 넘어오는 값들을 name으로 맵에 저장 후 반환 디폴트로 네임을 대문자로 변환해서 저장
	 * 
	 * @param request
	 * @return
	 */
	public static HashMap getParameterMap(HttpServletRequest request) {
		return getParameterMap(request, 1);
	}

	/**
	 * form에서 넘어오는 값들을 name으로 맵에 저장 후 반환
	 * 
	 * @param request
	 * @param capitalOption
	 *            - 1: 대문자, 2: 소문자, 3: 그대로
	 * @return
	 */
	private static HashMap<String, String> getParameterMap(HttpServletRequest request, int capiatlOption) {
		// 파라미터 이름
		Enumeration<String> paramNames = request.getParameterNames();

		// 저장할 맵
		HashMap<String, String> paramMap = new HashMap<String, String>();

		// 맵에 저장
		while (paramNames.hasMoreElements()) {
			String name = paramNames.nextElement().toString();
			String value = StringUtils.defaultIfEmpty(request.getParameter(name), "");

			if (capiatlOption == 1)
				paramMap.put(name.toUpperCase(), value);
			if (capiatlOption == 2)
				paramMap.put(name.toLowerCase(), value);
			if (capiatlOption == 3)
				paramMap.put(name, value);
		}
		
		// 맵에 저장
		return paramMap;
	}

	/**
	 * getParameterDataMap과 동일하되 리턴 DataMap
	 * 
	 * @param request
	 * @return
	 */
	public static DataMap getParameterDataMap(HttpServletRequest request) {
		return getParameterDataMap(request, 1);
	}

	/**
	 * getParameterDataMap과 동일하되 리턴 DataMap
	 * 
	 * @param request
	 * @param capiatlOption
	 * @return
	 */
	public static DataMap getParameterDataMap(HttpServletRequest request, int capiatlOption) {

		// 파라미터 이름
		Enumeration<String> paramNames = request.getParameterNames();

		// 저장할 맵
		DataMap paramMap = new DataMap();

		// 맵에 저장
		while (paramNames.hasMoreElements()) {
			String name = paramNames.nextElement().toString();
			String value = request.getParameter(name);
			paramMap.put(name.toUpperCase(), value);
		}
		//request.getSession().setAttribute("USER_ID","test");
		//paramMap.put("REGUSER", (String)request.getSession().getAttribute("AdmUserId"));
		//paramMap.put("MODUSER", (String)request.getSession().getAttribute("AdmUserId"));
				
		/* 세션 정보 세팅후 게시 예정 by Jade 2013-05-25
		 
		HttpSession httpSession = request.getSession();
		LoginSession sessionOffice = null;
		LoginSession sessionVisit = null;

		sessionOffice = (LoginSession) request.getSession().getAttribute(LoginSession.OFFICE_LOGIN_SESSION_KEY);
		sessionVisit = (LoginSession) request.getSession().getAttribute(LoginSession.VISIT_LOGIN_SESSION_KEY);
		
		if (sessionOffice != null) {
			paramMap.put("SESSION_YN", "Y");
			
			paramMap.put("AdmUserId", sessionOffice.getAdmUserId()); 
			paramMap.put("AdmUserName", sessionOffice.getAdmUserName());
			paramMap.put("AdmEmpNo", sessionOffice.getAdmEmpNo());
			paramMap.put("AdmDeptId", sessionOffice.getAdmDeptId()); 
			paramMap.put("REGUSER", sessionOffice.getAdmUserId());
			paramMap.put("MODUSER", sessionOffice.getAdmUserId());
			paramMap.put("USER_AUTH_CODE", sessionOffice.getRolleList());
		}
		if(sessionVisit != null){
			paramMap.put("depth1", (String)request.getParameter("depth1"));
			paramMap.put("depth2", (String)request.getParameter("depth2"));
			paramMap.put("depth3", (String)request.getParameter("depth3"));
			
			paramMap.put("SESSION_YN", "Y");

			paramMap.put("UserId", sessionVisit.getUSERID()); 
			paramMap.put("ChargeName", sessionVisit.getCAHRGENAME());
			paramMap.put("CommonUseYn", sessionVisit.getCOMMONUSEYN());
			paramMap.put("CommonUseCnt", sessionVisit.getCOMMONUSECNT()); 
			paramMap.put("GroupSiteId", sessionVisit.getGROUPSITEID());
			paramMap.put("GroupSpaceId", sessionVisit.getGROUPSPACEID());
			paramMap.put("CustomerSeqId", sessionVisit.getCUSTOMERSEQID());
			
		}
		if(sessionOffice == null && sessionVisit == null) {
			paramMap.put("SESSION_YN", "N");
			//paramMap.put("USER_AUTH_CODE", MessageUtil.getMessage("ROLE.D"));
		}*/
		
		// 결과 반환
		return paramMap;
	}

	/**
	 * 이메일주소 유효성 체크
	 * 
	 * @param email
	 * @return
	 */
	public static boolean isValidEmail(String email) {
		Pattern p = Pattern.compile("[a-zA-Z]*[0-9]*@[a-zA-Z]*.[a-zA-Z]*");
		Matcher m = p.matcher(email);
		return m.matches();
	}

	/**
	 * 휴대폰번호 유효성 체크
	 * 
	 * @param mobile
	 * @return
	 */
	public static boolean isValidMobileNum(String mobile) {
		if (mobile == null || !StringUtils.isNumeric(mobile) || mobile.length() < 10)
			return false;
		return true;
	}

	// 맵안의 내용들을 URL 로 구성하여 반환
	// URL 인코딩 처리함
	// * pExceptKey : 제외해야할 파라미터명(콤마구분)
	// : ex)"page,name1,..."
	// * pPrefix : '?' or '&' or '' - 셋중 하나
	public static String MapToUrl(HashMap pmap, String pExceptKey, String pPrefix) {
		String result = "";

		try {
			if (pmap != null) {
				pExceptKey = "," + PUtil.nullTrimReplace(pExceptKey).toLowerCase();
				pPrefix = PUtil.nullTrimReplace(pPrefix);

				Iterator v_keies = pmap.keySet().iterator();

				while (v_keies.hasNext()) {
					String v_key = (String) v_keies.next();
					String v_val = URLEncoder.encode(PUtil.nullTrimReplace(pmap.get(v_key)), "utf-8");
					String v_key_low = v_key.toLowerCase();

					// 현재 키이름이 제외대상에서 없으면, URL에 포함시킨다.
					if (pExceptKey.indexOf("," + v_key_low) == -1 && !"".equals(v_val)) {
						if (!result.equals("")) {
							result = result + "&" + v_key + "=" + v_val;
						} else {
							result = v_key + "=" + v_val;
						}
					}
				}

				if (!result.equals("")) {
					result = pPrefix + result;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}

		return result;
	}

	public static String MapToUrl(HttpServletRequest req, String pExceptKey, String pPrefix) {
		return MapToUrl(PUtil.getParameterMap(req, 3), pExceptKey, pPrefix);
	}

	// 맵안의 내용들 중에 지정한 대상 키들대상으로, URL 로 구성하여 반환
	// URL 인코딩 처리함
	// * pImportKey : 포함할 대상 파라미터명(콤마구분)
	// : ex)"page,name1,..."
	// * pPrefix : '?' or '&' or '' - 셋중 하나
	public static String MapToUrlDest(HashMap pmap, String pDestKey, String pPrefix) {
		String result = "";

		try {
			if (pmap != null) {
				pDestKey = "," + PUtil.nullTrimReplace(pDestKey).toLowerCase();
				pPrefix = PUtil.nullTrimReplace(pPrefix);

				Iterator v_keies = pmap.keySet().iterator();

				while (v_keies.hasNext()) {
					String v_key = (String) v_keies.next();
					String v_val = URLEncoder.encode(PUtil.nullTrimReplace(pmap.get(v_key)), "utf-8");
					String v_key_low = v_key.toLowerCase();

					// 현재 키이름이 제외대상에서 없으면, URL에 포함시킨다.
					if (pDestKey.indexOf("," + v_key_low) > -1 && !"".equals(v_val)) {
						if (!result.equals("")) {
							result = result + "&" + v_key + "=" + v_val;
						} else {
							result = v_key + "=" + v_val;
						}
					}
				}

				if (!result.equals("")) {
					result = pPrefix + result;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}

		return result;
	}

	public static String MapToUrlDest(HttpServletRequest req, String pDestKey, String pPrefix) {
		return MapToUrlDest(PUtil.getParameterMap(req, 3), pDestKey, pPrefix);
	}
	
	/**
	 * POJO class의 value를 DataMap형태로 변환한다.
	 * @param vo
	 * @return
	 * @see
	 * key: methodName toUpperCase
	 * value: invoke get methodName;
	 */
	public static DataMap objectToMap(Object vo) {
		DataMap data = new DataMap();
		Method[] methods = vo.getClass().getMethods();
		try 
		{
			for(Method method : methods)
			{
				String methodName = method.getName();
				if(methodName.startsWith("get") && !methodName.matches("getClass")) 
				{
					data.put(methodName.substring(3).toUpperCase(), method.invoke(vo));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return data;
	}

	/**
	 * DB에서 처리된 결과 반환값이 DataMap 객체이라하면 발생할 오류 사항에 대해 체크후 DataMap 객체를 반환한다.
	 * 
	 * @param dataMap
	 *            DB에서 반환된 또는 request로 전달 받은 DataMap 객체 또는 Object 객체 정보
	 * @return DataMap
	 */
	public static DataMap getNullCheckDataMap(Object dataMap) {
		DataMap resultDataMap = null;
		try {
			resultDataMap = dataMap != null ? (DataMap) dataMap : new DataMap();
		} catch (Exception e) {
			resultDataMap = new DataMap();
		}
		return resultDataMap;
	}

	/**
	 * DB에서 처리된 결과 반환값이 List 객체이라하면 발생할 오류 사항에 대해 체크후 List 객체를 반환한다.
	 * 
	 * @param dataMap
	 *            DB에서 반환된 또는 request로 전달 받은 List 객체 또는 Object 객체 정보
	 * @return DataMap
	 */
	public static List getNullCheckList(Object list) {
		List resultList = null;
		try {
			resultList = list != null ? (List) list : new Vector();
		} catch (Exception e) {
			resultList = new Vector();
		}
		return resultList;
	}

	/**
	 * DB에서 처리된 결과 반환값이 HashMap 객체이라하면 발생할 오류 사항에 대해 체크후 HashMap 객체를 반환한다.
	 * 
	 * @param hashMap
	 *            DB에서 반환된 또는 request로 전달 받은 HashMap 객체 또는 Object 객체 정보
	 * @return HashMap
	 */
	public static HashMap getNullCheckHashMap(Object hashMap) {
		HashMap resultHashMap = null;
		try {
			resultHashMap = hashMap != null ? (HashMap) hashMap : new HashMap();
		} catch (Exception e) {
			resultHashMap = new DataMap();
		}
		return resultHashMap;
	}

	/**
	 * HTML Tag 제거
	 * 
	 * @param tagStr
	 * @return
	 */
	public static String stripHtmlTag(String tagStr) {
		return tagStr != null ? tagStr.replaceAll("<(/)?([a-zA-Z]*)(\\s[a-zA-Z]*=[^>]*)?(\\s)*(/)?>", "") : "";
	}

	/**
	 * 파일명에 대한 리사이징 이름으로 변경 적용<br/>
	 * 이미지 확장자는 png로 변경 적용됨
	 * 
	 * @param fileName
	 *            변경 대상 파일명
	 * @param widthNum
	 *            변경 사이트 크기 수치 정보
	 * @return 변경된 파일명 (ex) sampleFilename_30.png)
	 */
	public static String reNameFilePng(String fileName, int widthNum) {
		String tmpFileName = StringUtils.defaultIfEmpty(fileName, ".");
		String firstFileInfo = tmpFileName.substring(0, tmpFileName.lastIndexOf(".") - 1);
		return !StringUtils.defaultIfEmpty(firstFileInfo, "").equals("") ? firstFileInfo + "_" + widthNum + ".png" : null;
	}

	// BingDecimal 타입을 문자열형으로 반환
	public static String bcToString(Object p_val) {
		BigDecimal v_bigNum = p_val == null ? new BigDecimal(0) : (BigDecimal) p_val;
		return v_bigNum.toString();
	}

	/**
	 * 게시판 본문내용에 개행문자가 있을경우 해당 문자를 <br>
	 * 태그로 변환한다.
	 * 
	 * @param content
	 * @return
	 */
	public static String parseContent(String content) {
		content = content.replaceAll("\n", "<br>");
		content = content.replaceAll(" ", "&nbsp;");

		return content;
	}

	public static void sysout(String p_title, Object p_print) {
		sysout(p_title, p_print == null ? "null" : p_print.toString());
	}

	public static void sysout(String p_title, String p_print) {
		String nowTime = PUtil.getFormatDate(new java.util.Date(), "yyyy-MM-dd HH:mm:ss");

		System.out.println("\n\n\n\n\n\n");
		System.out.println("================" + p_title + "================");
		System.out.println(nowTime);
		System.out.println(p_print);
		System.out.println("\n\n\n\n\n\n");
	}

	/**
	 * request 객체의 파라미터 정보를 추출 하여 페이지 이동 파라미터를 구성한다.
	 * 
	 * @param req
	 * @return
	 */
	public static String getParameters(HttpServletRequest req) {
		StringBuffer sb = new StringBuffer();
		Enumeration parmNames = req.getParameterNames();
		while (parmNames.hasMoreElements()) {
			String tmpParamName = (String) parmNames.nextElement();
			sb.append("&");
			sb.append(tmpParamName + "=" + req.getParameter(tmpParamName));
		}
		return sb.toString().length() > 1 ? sb.toString().substring(1) : "";
	}

	/**
	 * 랜덤으로 생성된 코드를 반환한다. Date : 2010. 9. 15. Author : jangjh
	 * 
	 * @param unitcnt
	 *            : 갯수, type : 1 -> 숫자, 2 -> 영문, 3 -> 혼합(영+숫)
	 * @return
	 */
	public static String getConfirmNoGenerator(int unitcnt, String type) {
		Random rnd = new Random();
		StringBuffer sb = new StringBuffer();

		for (int i = 0; i < unitcnt; i++) {
			if ("1".equals(type)) {
				sb.append((rnd.nextInt(10)));
			} else if ("2".equals(type)) {
				sb.append((char) ((int) (rnd.nextInt(26)) + 65));
			} else {
				if (rnd.nextBoolean()) {
					sb.append((char) ((int) (rnd.nextInt(26)) + 97));
				} else {
					sb.append((rnd.nextInt(10)));
				}
			}
		}

		return sb.toString().toUpperCase();
	}

	public static String getShortDateString() {
		java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("yyyyMMddHHmmss", java.util.Locale.KOREA);
		return formatter.format(new java.util.Date());
	}

	/**
	 * 
	 * 날짜 변환 exL 0415 -> 4/15 무조건 4자리 str을 받는다.
	 */

	public static String getTransDate(String str) {
		String result = "";
		int point = 0;

		if (str.length() == 4) {
			// 첫번째 문자열이 0이라면 ex: 0413
			point = str.indexOf("0");

			if (point == 0) {
				result = str.substring(0, 2) + "/" + str.substring(2, 4);
			} else {
				result = str.substring(0, 2) + "/" + str.substring(2, 4);
			}

		}

		return result;
	}

	public static String getTransDate2(String str) {
		String result = "";
		int point = 0;

		if (str.length() == 4) {
			// 첫번째 문자열이 0이라면 ex: 0413
			point = str.indexOf("0");

			if (point == 0) {
				result = str.substring(0, 2) + ":" + str.substring(2, 4);
			} else {
				result = str.substring(0, 2) + ":" + str.substring(2, 4);
			}

		}

		return result;
	}
	
	 public static String nvl(Object obj) {
	        return nvl(obj, "");
	    }

	    /**
	     * null 泥섎━
	     * 
	     * @param obj
	     * @return String
	     */
	    public static String nvl(Object obj, String ifNull) {
	        return ( obj != null && obj != "" ) ? obj.toString() : ifNull;
	    }
	    
	    /**
	     * null泥섎━ int濡�諛섑솚
	     * @param obj
	     * @param ifNull
	     * @return
	     */
	    public static int nvl(Object obj, int ifNull) {
	        return ( obj != null ) ? Integer.parseInt(obj.toString()) : ifNull;
	    }
	
	
		/**
		 * 
		 * 특수문자제거
		 */
	    public static String StringReplace(String str){       
	       String match = "[^\uAC00-\uD7A3xfe0-9a-zA-Z\\s]";
	       str =str.replaceAll(match, " ");
	       return str;
	    }
	    /**
		 * 
		 * 다운로드 URL가져오기
		 */
	    public static String getDownUrl(String str, int type){       
        
	    String address = "http://203.234.152.116/GetSourceURL/Pre_Download.aspx?list="+str+"&dtype="+type;
        String urlString = "";
        String current=""; 
        String[] addressArr = str.split(";");
        int errCnt = 0;
		
        try
        {
           URL url = new URL(address);
		   URLConnection urlConnection = url.openConnection();
		   BufferedReader in = new BufferedReader(
		   new InputStreamReader(urlConnection.getInputStream()));
		   while((current = in.readLine()) != null)
		   {
			  if(!current.substring(0, 5).equals("ERROR")){
		      urlString += current ;
			  }else{
				  urlString += current ;
				  errCnt++;
			  }
		   }
		   //예외처리
    	    if(addressArr.length != (urlString.split(",")).length){
    	    	errCnt = 2;
    	    }       
        	urlString = errCnt+urlString;
        	
       }catch(IOException e){
           e.printStackTrace();
       }
        return urlString;
		
    }
	    
	    
	    /**
		 * 
		 * 다운로드 URL목록가져오기
		 */
	    public static String getDownUrl(String str, String dType)  throws Exception {       
	    	StringBuffer buf = new StringBuffer();
		    //URL url = new URL("http://localhost:8080/InnoFD/InnoFD/test.jsp");
	    	URL url = new URL("http://203.234.152.116/GetSourceURL/Pre_Download.aspx");
		   
		    URLConnection httpConn = null;
		    BufferedReader in = null;
		    PrintWriter out = null;
	    	    try {
	    	        httpConn = url.openConnection();
	    	        httpConn.setDoOutput(true);  // <-- 이것이 핵심입니다.
	    	        httpConn.setUseCaches(false);
	    	        out = new PrintWriter (httpConn.getOutputStream());
	    	        
	    	        out.print("list="+str+"&dtype="+dType);
	    	        out.flush();

	    	        InputStream is = httpConn.getInputStream();
	    	        in = new BufferedReader(new InputStreamReader(is),8*1024);
	    	              
	    	        String line = null;
	    	        while( (line=in.readLine())!= null ){
	    	        	buf.append(line);
	    	        }
	    	      }catch(Exception err){
	    	    	  //System.out.println("########errMsg="+err.toString());
	    	      }
	    	      finally {
	    	        if ( out != null ) try {out.close();}catch(Exception e){}
	    	        if ( in != null ) try {in.close();}catch(Exception e){}
	    	      }
	    	   
	    	 return buf.toString();
	    }

	    // Search 메뉴 권한 구하기
	    public static String getPerms(List resultList, int p)
	    {
	    	String perms = "";
	    	for (int k=0; k<resultList.size(); k++)
			{
				if (!resultList.get(k).toString().equals("")) 
				{
					String menuCd = resultList.get(k).toString().split(",")[p];
					if (!menuCd.equals(""))
					{
						try {
							perms += menuCd.split("=")[1] + "/";
						}
						catch (Exception e) {
							e.printStackTrace();
						}
					}
					
				}
			}
	    	perms = perms.replaceAll("}","");
	    	return perms;
	    }
	    
	    //Search 권한을 위한 문자열 파싱
	    public static String[] getParse(String str, String div1, String div2)
	    {
	    	String[] divStr = str.split(div1);
	    	String[] parse = new String[divStr.length];
	    	for (int p=0; p<divStr.length; p++)
	    	{
	    		try 
	    		{
	    			if (!divStr[p].equals(""))
	    			{
	    				parse[p] = divStr[p].split(div2)[1].substring(0, 2);
	    			}	    			
	    		}
	    		catch (Exception e)
	    		{
	    			//e.printStackTrace();
	    		}
	    	}
	    	return parse;
	    }
	    
	    // 외신 권한에 따른 check box 만들기
	    public static String getForeignPerm(List resultList, String type)
	    {
	    	String checkBox = "";
	    	for (int k=0; k<resultList.size(); k++)
			{
				if (!resultList.get(k).toString().equals("")) 
				{
					String frCd = resultList.get(k).toString().split("-")[0].replace("{FR=", "");
					String frNm = resultList.get(k).toString().split("-")[1].replace("}", "");
					frNm = frNm.replace("미발행 사진", "");
					frNm = frNm.replace("발행 사진", "");
					if (type.equals("article")) checkBox += "<li><input type=\"checkbox\" name=\"foreignPress\" value=\""+frCd+"\" /> "+frNm+" </li>\n";
					else checkBox += "<input type=\"checkbox\" name=\"foreignPhoto\" value=\""+frCd+"\" /> "+frNm+" &nbsp;";
				}
			}
	    	return checkBox;
	    }
}